package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Grade;
import com.EAsystem.entity.Course;
import com.EAsystem.entity.Student;
import com.EAsystem.service.GradeService;
import com.EAsystem.service.CourseService;
import com.EAsystem.service.StudentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class GradeController {

    @Autowired
    private GradeService gradeService;
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private StudentService studentService;

    @GetMapping("/score")
    public String scorePage(@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "5") int size,
                           @RequestParam(required = false) Long courseId,
                           @RequestParam(required = false) Long studentId,
                           Model model) {
        
        // 获取所有课程和学生供筛选
        List<Course> allCourses = courseService.findAll();
        PageInfo<Student> studentPageInfo = studentService.findAllByPage(1, 1000); // 获取足够多的学生
        List<Student> allStudents = studentPageInfo.getList();
        
        // 根据条件查询成绩
        PageInfo<Grade> pageInfo;
        Grade searchGrade = new Grade();
        if (courseId != null && courseId > 0) {
            Course course = new Course();
            course.setId(courseId);
            searchGrade.setCourse(course);
        }
        if (studentId != null && studentId > 0) {
            Student student = new Student();
            student.setId(studentId);
            searchGrade.setStudent(student);
        }
        
        pageInfo = gradeService.findByConditionPage(searchGrade, page, size);
        
        model.addAttribute("grades", pageInfo.getList());
        model.addAttribute("allCourses", allCourses);
        model.addAttribute("allStudents", allStudents);
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchCourseId", courseId);
        model.addAttribute("searchStudentId", studentId);
        
        return "admin/score";
    }

    @GetMapping("/score/view/{id}")
    @ResponseBody
    public Map<String, Object> viewGrade(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            Grade grade = gradeService.findById(id);
            if (grade != null) {
                response.put("success", true);
                response.put("grade", grade);
            } else {
                response.put("success", false);
                response.put("message", "成绩记录不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取成绩记录失败：" + e.getMessage());
        }
        return response;
    }

    @PostMapping("/score/add")
    @ResponseBody
    public Map<String, Object> addGrade(@RequestParam Long studentId,
                                       @RequestParam Long courseId,
                                       @RequestParam(required = false) Double regularScore,
                                       @RequestParam(required = false) Double examScore) {
        Map<String, Object> response = new HashMap<>();
        try {
            Grade grade = new Grade();
            Student student = new Student();
            student.setId(studentId);
            Course course = new Course();
            course.setId(courseId);
            grade.setStudent(student);
            grade.setCourse(course);
            grade.setRegularScore(regularScore);
            grade.setExamScore(examScore);
            
            boolean success = gradeService.add(grade);
            if (success) {
                response.put("success", true);
                response.put("message", "成绩添加成功");
            } else {
                response.put("success", false);
                response.put("message", "成绩添加失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "成绩添加失败：" + e.getMessage());
        }
        return response;
    }

    @PostMapping("/score/updateRegular")
    @ResponseBody
    public Map<String, Object> updateRegularScore(@RequestParam Long id,
                                                  @RequestParam Double regularScore) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = gradeService.updateRegularScore(id.intValue(), regularScore);
            if (success) {
                response.put("success", true);
                response.put("message", "平时分更新成功");
            } else {
                response.put("success", false);
                response.put("message", "平时分更新失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "平时分更新失败：" + e.getMessage());
        }
        return response;
    }

    @PostMapping("/score/updateExam")
    @ResponseBody
    public Map<String, Object> updateExamScore(@RequestParam Long id,
                                              @RequestParam Double examScore) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = gradeService.updateExamScore(id.intValue(), examScore);
            if (success) {
                response.put("success", true);
                response.put("message", "考试分更新成功");
            } else {
                response.put("success", false);
                response.put("message", "考试分更新失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "考试分更新失败：" + e.getMessage());
        }
        return response;
    }

    @GetMapping("/score/delete/{id}")
    public String deleteGrade(@PathVariable Long id) {
        gradeService.delete(id.intValue());
        return "redirect:/admin/score";
    }

    @GetMapping("/score/batchDelete")
    public String batchDeleteGrades(@RequestParam("ids") String ids) {
        for (String id : ids.split(",")) {
            gradeService.delete(Integer.valueOf(id));
        }
        return "redirect:/admin/score";
    }
} 